/*
 *    Copyright (c) 2018-2025, 云集汇通 All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yunjihuitong.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 */

package com.yjht.common.func.shiro;

import com.alibaba.fastjson.JSONObject;
import com.yjht.common.utils.R;
import com.yjht.common.utils.ShiroFilterUtils;
import com.yjht.modules.sys.entity.SysUserEntity;
import lombok.Setter;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedList;

/**
 * @author lengleng
 * @date 2018/6/11
 */
public class KickoutSessionControlFilter extends AccessControlFilter {
    public static final String KICKOUT = "kickout";
    /**
     * 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
     */
    @Setter
    private boolean kickoutAfter = false;
    /**
     * 同一个帐号最大会话数 默认1
     */
    @Setter
    private int maxSession = 1;

    @Setter
    private SessionManager sessionManager;
    private Cache<String, Deque<Serializable>> cache;

    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("shiro-kickout-session");
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        if (!subject.isAuthenticated() && !subject.isRemembered()) {
            //如果没有登录，直接进行之后的流程
            return true;
        }

        Session session = subject.getSession();
        SysUserEntity userEntity = (SysUserEntity) subject.getPrincipal();
        Serializable sessionId = session.getId();

        Deque<Serializable> deque = cache.get(userEntity.getUsername());
        if (deque == null) {
            deque = new LinkedList<>();
            cache.put(userEntity.getUsername(), deque);
        }

        //如果队列里没有此sessionId，且用户没有被踢出；放入队列
        if (!deque.contains(sessionId) && session.getAttribute(KICKOUT) == null) {
            deque.push(sessionId);
            cache.put(userEntity.getUsername(), deque);
        }

        //如果队列里的sessionId数超出最大会话数，开始踢人
        while (deque.size() > maxSession) {
            Serializable kickoutSessionId = null;
            //如果踢出后者
            if (kickoutAfter) {
                kickoutSessionId = deque.removeFirst();
                //否则踢出前者
            } else {
                kickoutSessionId = deque.removeLast();
            }
            try {
                Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                if (kickoutSession != null) {
                    //设置会话的kickout属性表示踢出了
                    kickoutSession.setAttribute(KICKOUT, true);
                }
            } catch (Exception e) {
            }
        }

        //如果被踢出了，直接退出，重定向到踢出后的地址
        if (session.getAttribute(KICKOUT) != null) {
            //会话被踢出了
            try {
                subject.logout();
            } catch (Exception e) { //ignore
            }

            HttpServletResponse resp = (HttpServletResponse) response;
            HttpServletRequest req = (HttpServletRequest) request;
            if (ShiroFilterUtils.isAjax(req)) {
                JSONObject jsonObject = new JSONObject(R.error(HttpStatus.EXPECTATION_FAILED.value(), "该账号已在别处登录"));
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("application/json");
                resp.setStatus(HttpStatus.EXPECTATION_FAILED.value());
                response.getWriter().print(jsonObject);
            } else {
                WebUtils.issueRedirect(request, response, "/login.html?error");
            }

            return false;
        }

        return true;
    }
}